package com.jd.user.interceptor;

import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.Payload;
import com.jd.basic.jwt.RsaUtils;
import com.jd.system.annotation.PreAuthorize;
import com.jd.system.mapper.PermissionMapper;
import com.jd.user.domain.Logininfo;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;

@Controller
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
        // 有没有登录
        String token = request.getHeader("token");
        if (token != null) {
            Logininfo logininfo = null;
            try {
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //解密之后获取载荷数据
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                logininfo = payload.getLoginData().getLogininfo();

            } catch (ExpiredJwtException e) { //jwt过期时抛出的异常
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(" {\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }

//                // 刷新过期时间
//                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);


            if (logininfo.getType() == 1) { // 前端用户- 没有权限-不需要验证
                return true;
            }

            // 管理员  - 有权限 - 需要验证
            // 1.获取当前访问接口的自定义注解的sn
            HandlerMethod method = (HandlerMethod) handler;
            PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
            if (preAuthorize == null) {
                return true;
            } else {
                // 获取sn属性值
                String sn = preAuthorize.sn();
                // 获取当前登录人所有权限
                List<String> myPermissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());

                // 2.获取当前登录人的所以权限的sn
                // 3.判断：包含 - 有权限- 放行
                if (myPermissions.contains(sn)) {
                    return true;
                } else {
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
                    return false;

                }
            }
        }

            // 告诉浏览器返回一个json格式的数据
            response.setContentType("application/json;charset=UTF-8");

            response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");

            return false;
        }

}
